#include "errorlog.h"

void ErrorLog::initTable()
{
    QSqlQuery query;
    QString createTableSql = R"(
        CREATE TABLE IF NOT EXISTS error_log (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            timestamp DATETIME NOT NULL,
            device_name TEXT,
            error_message TEXT NOT NULL
        )
    )";

    if (!query.exec(createTableSql)) {
        qWarning() << "创建错误日志表失败:" << query.lastError().text();
    } else {
        qDebug() << "错误日志表初始化成功";
    }

    // 创建时间索引以提高查询性能
    QString createIndexSql =
        "CREATE INDEX IF NOT EXISTS idx_error_timestamp ON error_log(timestamp)";
    if (!query.exec(createIndexSql)) {
        qWarning() << "创建时间索引失败:" << query.lastError().text();
    }

    // 创建设备名称索引
    QString createDeviceIndexSql =
        "CREATE INDEX IF NOT EXISTS idx_error_device_name ON error_log(device_name)";
    if (!query.exec(createDeviceIndexSql)) {
        qWarning() << "创建设备名称索引失败:" << query.lastError().text();
    }
}

bool ErrorLog::insertError(const QDateTime &timestamp, const QString &deviceName,
                           const QString &errorMessage)
{
    QSqlQuery query;
    query.prepare("INSERT INTO error_log (timestamp, device_name, error_message) VALUES (?, ?, ?)");
    query.addBindValue(timestamp);
    query.addBindValue(deviceName);
    query.addBindValue(errorMessage);

    if (!query.exec()) {
        qWarning() << "插入错误记录失败:" << query.lastError().text();
        return false;
    }

    return true;
}

QVector<QVariantMap> ErrorLog::queryByDate(const QDate &date, const QString &deviceName)
{
    QVector<QVariantMap> results;
    QSqlQuery query;

    QString sql = "SELECT id, timestamp, device_name, error_message FROM error_log WHERE 1=1";

    if (date.isValid()) {
        sql += " AND DATE(timestamp) = ?";
    }
    if (!deviceName.isEmpty()) {
        sql += " AND device_name = ?";
    }

    sql += " ORDER BY timestamp DESC";

    query.prepare(sql);

    int bindIndex = 0;
    if (date.isValid()) {
        query.addBindValue(date);
        bindIndex++;
    }
    if (!deviceName.isEmpty()) {
        query.addBindValue(deviceName);
    }

    if (!query.exec()) {
        qWarning() << "按日期查询错误记录失败:" << query.lastError().text();
        return results;
    }

    while (query.next()) {
        QVariantMap record;
        record["id"] = query.value("id");
        record["timestamp"] = query.value("timestamp");
        record["device_name"] = query.value("device_name");
        record["error_message"] = query.value("error_message");
        results.append(record);
    }

    return results;
}

int ErrorLog::getTotalRecords(const QDate &date, const QString &deviceName)
{
    QSqlQuery query;

    QString sql = "SELECT COUNT(*) FROM error_log WHERE 1=1";

    if (date.isValid()) {
        sql += " AND DATE(timestamp) = ?";
    }
    if (!deviceName.isEmpty()) {
        sql += " AND device_name = ?";
    }

    query.prepare(sql);

    int bindIndex = 0;
    if (date.isValid()) {
        query.addBindValue(date);
        bindIndex++;
    }
    if (!deviceName.isEmpty()) {
        query.addBindValue(deviceName);
    }

    if (!query.exec()) {
        qWarning() << "获取错误记录总数失败:" << query.lastError().text();
        return 0;
    }

    if (query.next()) {
        return query.value(0).toInt();
    }

    return 0;
}

QVector<QVariantMap> ErrorLog::queryByPage(int page, int pageSize, const QDate &date,
                                           const QString &deviceName)
{
    QVector<QVariantMap> results;
    QSqlQuery query;

    int offset = (page - 1) * pageSize;

    QString sql = "SELECT id, timestamp, device_name, error_message FROM error_log WHERE 1=1";

    if (date.isValid()) {
        sql += " AND DATE(timestamp) = ?";
    }
    if (!deviceName.isEmpty()) {
        sql += " AND device_name = ?";
    }

    sql += " ORDER BY timestamp DESC LIMIT ? OFFSET ?";

    query.prepare(sql);

    int bindIndex = 0;
    if (date.isValid()) {
        query.addBindValue(date);
        bindIndex++;
    }
    if (!deviceName.isEmpty()) {
        query.addBindValue(deviceName);
        bindIndex++;
    }
    query.addBindValue(pageSize);
    query.addBindValue(offset);

    if (!query.exec()) {
        qWarning() << "分页查询错误记录失败:" << query.lastError().text();
        return results;
    }

    while (query.next()) {
        QVariantMap record;
        record["id"] = query.value("id");
        record["timestamp"] = query.value("timestamp");
        record["device_name"] = query.value("device_name");
        record["error_message"] = query.value("error_message");
        results.append(record);
    }

    return results;
}

bool ErrorLog::cleanOldRecords(int keepDays)
{
    QSqlQuery query;
    QDateTime cutoffTime = QDateTime::currentDateTime().addDays(-keepDays);

    query.prepare("DELETE FROM error_log WHERE timestamp < ?");
    query.addBindValue(cutoffTime);

    if (!query.exec()) {
        qWarning() << "清理过期错误记录失败:" << query.lastError().text();
        return false;
    }

    int deletedCount = query.numRowsAffected();
    qDebug() << "清理过期错误记录成功，删除了" << deletedCount << "条记录";
    return true;
}